/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.zkex.simple;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.type.FieldVo;
import cn.easyplatform.web.ext.Widget;
import cn.easyplatform.web.ext.zul.Buttongroup;
import cn.easyplatform.web.task.OperableHandler;
import cn.easyplatform.web.task.event.EventListenerHandler;
import cn.easyplatform.web.task.zkex.ListSupport;
import cn.easyplatform.web.utils.PageUtils;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Row;
import org.zkoss.zul.Rows;

import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class ButtongroupBuilder extends AbstractQueryBuilder<Buttongroup> implements Widget,
        EventListener<Event> {

    public ButtongroupBuilder(OperableHandler mainTaskHandler, Buttongroup bg) {
        super(mainTaskHandler, bg);
    }

    public ButtongroupBuilder(ListSupport support, Buttongroup bg,
                              Component anchor) {
        super(support, bg, anchor);
    }

    @Override
    public Component build() {
        if (me.getCols() <= 0)
            throw new EasyPlatformWithLabelKeyException(
                    "component.property.not.found", "<buttongroup>", "cols");
        PageUtils.checkAccess(main.getAccess(), me);
        me.setAttribute("$proxy", this);
        if (Strings.isBlank(me.getSize()))
            me.setSize("sm");
        if (Strings.isBlank(me.getSclass()))
            me.setSclass("z-form");
        else
            me.setSclass(me.getSclass() + " z-form");
        if (me.isImmediate())
            createButtons(me);
        if (Strings.isBlank(me.getOddRowSclass()))
            me.setOddRowSclass("none");
        return me;
    }

    private void createButtons(Buttongroup me) {
        if (!Strings.isBlank(me.getButtons())) {
            String[] labels = me.getButtons().split(",");
            Component rows = new Rows();
            me.appendChild(rows);
            Component parent = null;
            int index = 0;
            StringBuilder sb = new StringBuilder();
            for (String label : labels) {
                if (index % me.getCols() == 0) {
                    parent = new Row();
                    rows.appendChild(parent);
                }
                parent.appendChild(createButton(label, index, sb));
                index++;
            }
        } else load();
    }

    protected void createModel(List<?> data) {
        int index = 0;
        Component rows = null;
        Component parent = null;
        boolean hasEmptyLabel = !Strings.isBlank(me.getEmptyLabel());
        StringBuilder sb = new StringBuilder();
        if (hasEmptyLabel) {
            index = 1;
            rows = new Rows();
            me.appendChild(rows);
            parent = new Row();
            rows.appendChild(parent);
            parent.appendChild(createButton(
                    me.getEmptyLabel(),
                    Strings.isBlank(me.getEmptyValue()) ? 0 : me
                            .getEmptyValue(), sb));
        }
        if (!data.isEmpty()) {
            if (rows == null) {
                rows = new Rows();
                me.appendChild(rows);
            }
            int size = hasEmptyLabel ? data.size() + 1 : data.size();
            for (; index < size; index++) {
                if (index % me.getCols() == 0) {
                    parent = new Row();
                    rows.appendChild(parent);
                }
                Object[] fvs = (Object[]) data.get(hasEmptyLabel ? index - 1
                        : index);
                if (fvs.length == 1) {
                    if (fvs[0] instanceof FieldVo)
                        parent.appendChild(createButton((String) ((FieldVo) fvs[0]).getValue(), index, sb));
                    else
                        parent.appendChild(createButton(
                                (String) fvs[0], index, sb));
                } else if (fvs.length == 2) {
                    if (fvs[0] instanceof FieldVo) {
                        parent.appendChild(createButton((String) ((FieldVo) fvs[1]).getValue(), ((FieldVo) fvs[0]).getValue(), sb));
                    } else {
                        parent.appendChild(createButton(
                                (String) fvs[1],
                                fvs[0], sb));
                    }
                }
            }
        }
    }

    private Button createButton(String label, Object value, StringBuilder sb) {
        sb.setLength(0);
        Button btn = new Button(label);
        btn.setHflex("1");
        btn.setAttribute("value", value);
        sb.append("btn btn-block btn-").append(me.getJackOff());
        if (!Strings.isBlank(me.getSize()))
            sb.append(" btn-").append(me.getSize());
        btn.setZclass(sb.toString());
        btn.setStyle(me.getItemStyle());
        btn.setDisabled(me.isDisabled());
        btn.addEventListener(Events.ON_CLICK, this);
        return btn;
    }

    @Override
    public void onEvent(Event event) throws Exception {
        me.setValue(event.getTarget().getAttribute("value"));
        if (!Strings.isBlank(me.getEvent())) {
            EventListenerHandler el = new EventListenerHandler(Events.ON_CLICK, main,
                    me.getEvent(), anchor);
            el.onEvent(new Event(Events.ON_CLICK, event.getTarget(), event
                    .getTarget().getAttribute("value")));
        }
    }

    @Override
    public void reload(Component rg) {
        rg.getChildren().clear();
        createButtons((Buttongroup) rg);
    }
}
